//
//  HMEmoticonModel.swift
//  68.新工程-表情键盘_界面搭建
//
//  Created by shenzhenIOS on 16/4/20.
//  Copyright © 2016年 shenzhenIOS. All rights reserved.
//

import UIKit

/// 表情模型, 包含中文名称(传输名称),图片名称
class HMEmoticonModel: NSObject, NSCoding {
    /// 表情模型所在文件夹
    var id: String
    
    /// 中文名称(传输名称)
    var chs: String?
    
    /// 图片名称
    var png: String? {
        didSet {
            // 图片全路径 = Emoticons.bundle/id/png
            fullPngPath = EmoticonsBundlePath + "/" + id + "/" + png!
        }
    }
    
    var fullPngPath: String?
    
//    /// 图片全路径
//    var fullPngPath: String?
    
    /// emoji表情,使用
    var code: String? {
        didSet {
            // KVC设置code后,将code转成emoji
            // 扫描 String -> Int
            let scanner = NSScanner(string: code!)
            
            var result: UInt32 = 0
            // result: UnsafeMutablePointer<UInt32>: 需要一个UInt32类型的可变指针
            scanner.scanHexInt(&result)
            
            let scalar = UnicodeScalar(result)
            let c = Character(scalar)
            emoji = String(c)
        }
    }
    
    /// emoji属性
    var emoji: String?
    
    // 字典转模型
    init(dict: [String: String], id: String) {
        self.id = id
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // 打印
    override var description: String {
        get {
//            let keys = ["chs", "png"]
            return "\n\t\t:表情模型: chs: \(chs), png: \(png), code: \(code), fullPngPath: \(fullPngPath)"
        }
    }
    
    // 归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(id, forKey: "id")
        aCoder.encodeObject(chs, forKey: "chs")
        aCoder.encodeObject(png, forKey: "png")
        aCoder.encodeObject(code, forKey: "code")
        aCoder.encodeObject(emoji, forKey: "emoji")
    }
    
    required init?(coder aDecoder: NSCoder) {
        self.id = aDecoder.decodeObjectForKey("id") as? String ?? ""
        self.chs = aDecoder.decodeObjectForKey("chs") as? String
        self.png = aDecoder.decodeObjectForKey("png") as? String
        self.code = aDecoder.decodeObjectForKey("code") as? String
        self.emoji = aDecoder.decodeObjectForKey("emoji") as? String
        super.init()
        
        if self.png != nil {
            self.fullPngPath = EmoticonsBundlePath + "/" + id + "/" + png!
        }
    }
}
